#!/bin/sh
#
# Copyright (C) 2000-2022 Kern Sibbald
# License: BSD 2-Clause; see file LICENSE-FOSS
#
#  Test MaxWaitTime, MaxRunTime and MaxStartDelay
#

TestName="maxtime-test"
JobName=backup

. scripts/functions

copy_test_confs

rm -f ${cwd}/tmp/RUN*log
cp -f ${cwd}/scripts/bacula-dir.conf.maxtime ${cwd}/bin/bacula-dir.conf
WHEN=`date '+%Y-%m-%d %H:%M:%S'`

echo "${cwd}/build/po" >${cwd}/tmp/file-list

if [ "$FORCE_DEDUP" = yes ]; then
    $bperl -e 'add_attribute("$conf/bacula-dir.conf", "Maximum Volume Bytes", "1MB", "Pool", "Default");'
fi

start_test

cat <<END_OF_DATA >${cwd}/tmp/bconcmds
@output /dev/null
messages
@$out ${cwd}/tmp/log1.out
label volume=TestVolume001 pool=PoolA
@$out ${cwd}/tmp/RUN_MAXTIME.log
@# no media => have to wait
@# JobId 1
run job=RUN_MAXWAITTIME comment="Should fail" pool=Default yes
@sleep 2
@# storage is used by RUN_MAXWAITTIME => have to wait
@# JobId 2
run job=RUN_MAXSTARTDELAY comment="Should fail" pool=PoolA when="$WHEN" yes
@sleep 2
@# storage is used by the first MAXWAITTIME, but should work
@# JobId 3
run job=RUN_MAXWAITTIME comment="Should work" pool=PoolA yes
@sleep 60
label volume=TestVolume002 pool=Default
mount
@sleep 2
mount
wait
messages
@# JobId 4
run job=RUN_MAXRUNTIME comment="Should fail" pool=PoolA yes
wait
messages
status dir
status client
@sleep 2
quit
END_OF_DATA

(mkfifo ${cwd}/tmp/fifo 
 mkfifo ${cwd}/tmp/fifo2
 mkfifo ${cwd}/tmp/fifo3) 2> /dev/null

run_bacula
check_for_zombie_jobs storage=File
stop_bacula

rm -f ${cwd}/tmp/fifo ${cwd}/tmp/fifo2 ${cwd}/tmp/fifo3

dstat=0
bstat=0
rstat=0
touch ${cwd}/tmp/log2.out

grep -e '1: Fatal error: Max wait time exceeded. Job canceled.' ${cwd}/tmp/RUN_MAXTIME.log >/dev/null
if [ $? -eq 0 ]
then
    [ "$debug" = 1 ] && echo MAXWAITTIME ok
else
   echo "MAXWAITTIME in error"
   bstat=1
fi

grep -e '2: Fatal error: Job canceled because max start delay time exceeded.' ${cwd}/tmp/RUN_MAXTIME.log > /dev/null
f=$?

grep -e 'NEVER start this' ${cwd}/tmp/RUN_MAXTIME.log >/dev/null
s=$?

if [ $f -eq 0 -a $s -ne 0 ]
then
    [ "$debug" = 1 ] && echo MAXSTARTDELAY ok
else
   echo "MAXSTARTDELAY in error"
   bstat=1
fi

grep -e '4: Fatal error: Max run time exceeded. Job canceled.' ${cwd}/tmp/RUN_MAXTIME.log >/dev/null 
if [ $? -eq 0 ]
then
    [ "$debug" = 1 ] && echo MAXRUNTIME ok
else
   echo "MAXRUNTIME in error"
   bstat=1
fi

grep 'Termination: *Backup OK' ${cwd}/tmp/RUN_MAXTIME.log >/dev/null
if [ $? -eq 0 ]
then
    [ "$debug" = 1 ] && echo MAXRUNTIME2 ok
else
   echo "MAXRUNTIME2 in error"
   bstat=1
fi


end_test
